<?php
/**
 * Class FPVController
 */

class FPVController extends WP_REST_Controller {

    public function __construct(){
        $this->namespace = 'fpvone/v1';
        $this->module = 'parts';

//        //跨域
//        header("Access-Control-Allow-Credentials: true");
//        header("Access-Control-Allow-Origin: *");
//        //CORS
//        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
//        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线
    }
    public function register_routes()
    {
        //发布FPV配置
        register_rest_route($this->namespace, '/fpv-post', [
            [
                'callback' => [$this, 'fpv_post'],
                'methods' => 'POST'
            ]
        ]);
        //发布FPV配置
        register_rest_route($this->namespace, '/save-parts', [
            [
                'callback' => [$this, 'save_parts'],
                'methods' => 'POST'
            ]
        ]);
        //保存配置清单
        register_rest_route($this->namespace, '/save-build-list', [
            [
                'callback' => [$this, 'save_build_list'],
                'methods' => 'POST'
            ]
        ]);
        //添加图片
        register_rest_route($this->namespace, '/add-img', [
            [
                'callback' => [$this, 'add_img'],
                'methods' => 'POST'
            ]
        ]);
        //搜索配件
        register_rest_route($this->namespace, '/search-parts', [
            [
                'callback' => [$this, 'search_parts'],
                'methods' => 'POST'
            ]
        ]);
    }

    public function fpv_post(){
        $spider_fpv_id = isset($_POST['spider_fpv_id']) ? $_POST['spider_fpv_id'] : 0;
        $title = isset($_POST['title']) ? $_POST['title'] : '';
        $img = isset($_POST['img']) ? $_POST['img'] : '';
        $category_id = isset($_POST['category_id']) ? $_POST['category_id'] : 0;
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $tags_input = isset($_POST['tags_input']) ? $_POST['tags_input'] : '';
        $photos = isset($_POST['photos']) ? $_POST['photos'] : '';

        if(!$spider_fpv_id || !$title || !$img || !$category_id || !$content || !$tags_input){
            return json_encode([
                'code' => 0,
                'msg' => '不能为空'
            ]);
        }

        //先保存文章
        $post = [];
        $post['post_author'] = 1;
        $post['post_date'] = date("Y-m-d H:i:s",time());
        $post['post_date_gmt'] = gmdate("Y-m-d H:i:s",time());
        $post['post_content'] = $content;
        $post['post_title'] = $title;
        $post['post_name'] = $title;
        $post['post_category'] = [$category_id];
        $post['tags_input'] = explode(',',$tags_input);
        $post_id = wp_insert_post($post);//发布文章

        //把图片上传到云端cos
        if($photos){
            $photos = explode(',', $photos);
            foreach ($photos as $photo){
                upload_img_to_cos(ABSPATH.$photo , $photo);
            }
        }

        //给文章加缩略图
        //check file type
        $filetype = wp_check_filetype($img, null);
        //set attachment data
        $attachment = [
            'post_mime_type' => $filetype['type'],
            'post_title' => $title,//sanitize_file_name(basename($img)),
            'post_excerpt' => $title,
            'post_content' => $title,
            'post_status' => 'inherit',
        ];
        //create attachment
        $attachment_id = wp_insert_attachment($attachment, $img, $post_id);
        //include image.php
        require_once ABSPATH . "wp-admin/includes/image.php";
        //define attachment metadata
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $img);
        //assign metadata to attachment
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        //and finally assign featured image to post
        set_post_thumbnail($post_id,$attachment_id);

        #把配置关联到spider_fpv表
        global $wpdb;
        $wpdb->update('spider_fpv',['wp_posts_id'=>$post_id],['id'=>$spider_fpv_id]);

        return json_encode([
            'code' => 1,
            'msg' => '成功',
            'post_id' => $post_id
        ]);

    }

    public function save_parts(){
        $id = isset($_POST['id']) ? $_POST['id'] : 0;
        $type = isset($_POST['type']) ? $_POST['type'] : 0;
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $img = isset($_POST['img']) ? $_POST['img'] : '';
        $origin_url = isset($_POST['origin_url']) ? $_POST['origin_url'] : '';
        $url = isset($_POST['url']) ? $_POST['url'] : '';
        $price = isset($_POST['price']) ? $_POST['price'] : '';

        if(!$type || !$name || !$img || !$origin_url){
            return json_encode([
                'code' => 0,
                'msg' => '参数不能为空'
            ]);
        }

        //处理url
        if($url){
            $parse_url = parse_url($url);
            parse_str($parse_url['query'],$query_arr);
            if(isset($query_arr['id'])){
                $url = $parse_url['scheme']."://".$parse_url['host'].$parse_url['path']."?id=".$query_arr['id'];
            }else{
                return json_encode([
                    'code' => 0,
                    'msg' => '请检查淘宝链接是否正确'
                ]);
            }
        }

        global $wpdb;
        //下载远程图片
        //(获取路径)
        if(substr($img,0,4)=="data"){return json_encode([
            'code' => 0,
            'msg' => 'data开头的都不对'
        ]);}
        if(substr($img,0,4)=="http"){
            if($id){
                $parts = $wpdb->get_row("select * from parts where id =".$id);
                $path = $parts->img;
            }else{
                $path = "/wp-content/uploads/".date("Y/m",time())."/".uniqid("parts_").".jpg";
            }
            download_image($img, $path);//图片为真，会保留；图片为假，会删除

            //图片如果不存在，则表示已经被download_image函数销毁
            if(!file_exists(ABSPATH.$path)){
                return json_encode([
                    'code' => 0,
                    'msg' => '搞错了吧？这个是图片URL吗？找个正确的图片地址吧'
                ]);
            }
            upload_img_to_cos(ABSPATH.$path, $path);
        }else{
            $path = $img;
        }

        //保存parts信息
        if($id){
            $wpdb->update("parts",[
                'parts_type_id' => $type,
                'name' => $name,
                'img' => $path,
                'origin_url' => $origin_url,
                'url' => $url,
                'price' => $price,
                'update_time' => date("Y-m-d H:i:s",time()),
            ],['id'=>$id]);
        }else{
            $wpdb->insert("parts",[
                'parts_type_id' => $type,
                'name' => $name,
                'img' => $path,
                'origin_url' => $origin_url,
                'url' => $url,
                'price' => $price,
                'create_time' => date("Y-m-d H:i:s",time()),
                'update_time' => date("Y-m-d H:i:s",time())
            ]);

            $id = $wpdb->insert_id;
        }

        return json_encode([
            'code' => 1,
            'msg' => '成功',
            'id' => $id,
            'img' => $path,
            'url' => $url,
        ]);
    }

    public function save_build_list(){
        $fpv_id = isset($_POST['fpv_id']) ? $_POST['fpv_id'] : 0;
        $ids = isset($_POST['ids']) ? $_POST['ids'] : '';
        if(!$ids || !$fpv_id){
            return json_encode([
                'code' => 0,
                'msg' => '不能为空'
            ]);
        }

        $ids = explode(',', $ids);
        global $wpdb;
        foreach ($ids as $id){
            $row = $wpdb->get_row("select * from fpv_parts where fpv_id=".$fpv_id." and parts_id=".$id);
            if($row){
                //更新
                // DO Nothing
            }else{
                //添加
                $wpdb->insert('fpv_parts',[
                    'fpv_id' => $fpv_id,
                    'parts_id' => $id,
                    'create_time' => date("Y-m-d H:i:s",time()),
                    'update_time' => date("Y-m-d H:i:s",time())
                ]);
            }
        }
        return json_encode([
            'code' => 1,
            'msg' => '更新成功'
        ]);
    }

    public function add_img(){
        // 如果没有图片，就单独添加
        $img = isset($_POST['img']) ? $_POST['img'] : '';

        if(!$img){
            return json_encode([
                'code' => 0,
                'msg' => '不能为空'
            ]);
        }

        $path = "/wp-content/uploads/".date("Y/m",time())."/".uniqid("parts_").".jpg";
        download_image($img, $path);
        $tiny_path = $path . tinyjpg();
//        download_image($img, $tiny_path);//无需下载tinypng

        upload_img_to_cos(ABSPATH . $path, $path);
//        upload_img_to_cos(ABSPATH . $tiny_path, $tiny_path);

        return json_encode([
            'code' => 1,
            'msg' => '成功',
            'url' => $path
        ]);

    }

    public function search_parts(){
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        if(!$name){
            return json_encode([
                'code' => 0,
                'msg' => '搜索词为空！'
            ]);
        }

        global $wpdb;
        $parts = $wpdb->get_results("select * from parts where name like '%{$name}%'");

        return json_encode([
            'code' => 1,
            'msg' => '成功',
            'data' => $parts
        ]);
    }

    function isImage($imgPath){
        $file  = fopen($imgPath, "rb");
        $bin  = fread($file, 2); // 只读2字节

        fclose($file);
        // 标识前两个字符按照，c格式，数组索引chars1、chars2
        $strInfo = unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';

        if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/) {
            return $typeCode;
        }else {
            return false;
        }
    }

}